/**
 * 账户管理路由
 */
const express = require('express');
const router = express.Router();
const { generateId } = require('../utils/helpers');
const {
    readUserAccounts,
    saveUserAccounts,
    readAdminAccounts,
    saveAdminAccounts
} = require('../services/accountService');

/**
 * 获取用户账号列表
 * GET /api/accounts/users
 */
router.get('/users', async (req, res) => {
    try {
        const data = await readUserAccounts();
        res.json({
            success: true,
            data: data.accounts
        });
    } catch (error) {
        console.error('❌ 获取用户账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 创建用户账号
 * POST /api/accounts/users
 */
router.post('/users', async (req, res) => {
    try {
        const { username, password, name } = req.body;
        
        if (!username || !password) {
            return res.status(400).json({
                success: false,
                error: '用户名和密码不能为空'
            });
        }
        
        const data = await readUserAccounts();
        
        // 检查用户名是否已存在
        if (data.accounts.find(acc => acc.username === username)) {
            return res.status(400).json({
                success: false,
                error: '用户名已存在'
            });
        }
        
        const newAccount = {
            id: generateId('user'),
            username,
            password,
            name: name || username,
            createdAt: new Date().toISOString(),
            lastLogin: null,
            isDefault: false
        };
        
        data.accounts.push(newAccount);
        await saveUserAccounts(data);
        
        res.json({
            success: true,
            message: '用户账号创建成功',
            data: newAccount
        });
        
    } catch (error) {
        console.error('❌ 创建用户账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新用户账号
 * PUT /api/accounts/users/:id
 */
router.put('/users/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { username, password, name } = req.body;
        
        const data = await readUserAccounts();
        const accountIndex = data.accounts.findIndex(acc => acc.id === id);
        
        if (accountIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '用户账号不存在'
            });
        }
        
        // 检查用户名是否已被其他账号使用
        if (username && data.accounts.find(acc => acc.username === username && acc.id !== id)) {
            return res.status(400).json({
                success: false,
                error: '用户名已被使用'
            });
        }
        
        const account = data.accounts[accountIndex];
        if (username) account.username = username;
        if (password) account.password = password;
        if (name) account.name = name;
        account.updatedAt = new Date().toISOString();
        
        await saveUserAccounts(data);
        
        res.json({
            success: true,
            message: '用户账号更新成功',
            data: account
        });
        
    } catch (error) {
        console.error('❌ 更新用户账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 删除用户账号
 * DELETE /api/accounts/users/:id
 */
router.delete('/users/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        const data = await readUserAccounts();
        const accountIndex = data.accounts.findIndex(acc => acc.id === id);
        
        if (accountIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '用户账号不存在'
            });
        }
        
        const account = data.accounts[accountIndex];
        
        // 不允许删除默认账号
        if (account.isDefault) {
            return res.status(400).json({
                success: false,
                error: '不能删除默认用户账号'
            });
        }
        
        data.accounts.splice(accountIndex, 1);
        await saveUserAccounts(data);
        
        res.json({
            success: true,
            message: '用户账号删除成功'
        });
        
    } catch (error) {
        console.error('❌ 删除用户账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取管理员账号列表
 * GET /api/accounts/admins
 */
router.get('/admins', async (req, res) => {
    try {
        const data = await readAdminAccounts();
        res.json({
            success: true,
            data: data.accounts
        });
    } catch (error) {
        console.error('❌ 获取管理员账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 创建管理员账号
 * POST /api/accounts/admins
 */
router.post('/admins', async (req, res) => {
    try {
        const { username, password, name, role } = req.body;
        
        if (!username || !password) {
            return res.status(400).json({
                success: false,
                error: '用户名和密码不能为空'
            });
        }
        
        const data = await readAdminAccounts();
        
        // 检查用户名是否已存在
        if (data.accounts.find(acc => acc.username === username)) {
            return res.status(400).json({
                success: false,
                error: '管理员用户名已存在'
            });
        }
        
        const newAccount = {
            id: generateId('admin'),
            username,
            password,
            name: name || username,
            role: role || 'admin',
            createdAt: new Date().toISOString(),
            lastLogin: null,
            isDefault: false
        };
        
        data.accounts.push(newAccount);
        await saveAdminAccounts(data);
        
        res.json({
            success: true,
            message: '管理员账号创建成功',
            data: newAccount
        });
        
    } catch (error) {
        console.error('❌ 创建管理员账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新管理员账号
 * PUT /api/accounts/admins/:id
 */
router.put('/admins/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { username, password, name, role } = req.body;
        
        const data = await readAdminAccounts();
        const accountIndex = data.accounts.findIndex(acc => acc.id === id);
        
        if (accountIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '管理员账号不存在'
            });
        }
        
        // 检查用户名是否已被其他账号使用
        if (username && data.accounts.find(acc => acc.username === username && acc.id !== id)) {
            return res.status(400).json({
                success: false,
                error: '管理员用户名已被使用'
            });
        }
        
        const account = data.accounts[accountIndex];
        if (username) account.username = username;
        if (password) account.password = password;
        if (name) account.name = name;
        if (role) account.role = role;
        account.updatedAt = new Date().toISOString();
        
        await saveAdminAccounts(data);
        
        res.json({
            success: true,
            message: '管理员账号更新成功',
            data: account
        });
        
    } catch (error) {
        console.error('❌ 更新管理员账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 删除管理员账号
 * DELETE /api/accounts/admins/:id
 */
router.delete('/admins/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        const data = await readAdminAccounts();
        const accountIndex = data.accounts.findIndex(acc => acc.id === id);
        
        if (accountIndex === -1) {
            return res.status(404).json({
                success: false,
                error: '管理员账号不存在'
            });
        }
        
        const account = data.accounts[accountIndex];
        
        // 不允许删除默认管理员账号
        if (account.isDefault) {
            return res.status(400).json({
                success: false,
                error: '不能删除默认管理员账号'
            });
        }
        
        data.accounts.splice(accountIndex, 1);
        await saveAdminAccounts(data);
        
        res.json({
            success: true,
            message: '管理员账号删除成功'
        });
        
    } catch (error) {
        console.error('❌ 删除管理员账号失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

module.exports = router;

